package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import  java.io.IOException;


//记录日志异常信息
@Slf4j
@Service
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private UploadProperties prop;//自动注入全局配置文件---减少静态变量(把规定的图片格式和访问的基础路径配置到配置文件中)

    //private  static  final List<String> ALLOW_TYPES= Arrays.asList("image/jpeg","image/png","image/bmp");
    public String uploadImage(MultipartFile file){

        try {
            //校验文件类型
            String contentType = file.getContentType();
            if (!prop.getAllowTypes().contains(contentType)){
                throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
            }
            //校验文件内容  因为校验文件类型很容易被突破
            BufferedImage image = ImageIO.read(file.getInputStream());//如果不是图片流返回值为空
            if (image == null){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
             //准备目标路径
             //File dest = new File("/Users/hehao/project_resources/image/",file.getOriginalFilename());
             //保存文件到本地
             //file.transferTo(dest);
            //上传到Linux服务器的FastDFS模块

            //获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(),".");
            StorePath storePath  =fastFileStorageClient.uploadFile(file.getInputStream(),file.getSize(),extension,null);
            //返回路劲
            //return  prop.getBaseurl()+storePath.getFullPath();u
            return prop.getBaseurl()+storePath.getFullPath();

        } catch (IOException e) {
          //上传文件失败
          log.error("【文件上传失败】上传文件失败",e);
          throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }

    }

}
